package com.it.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.util.SaResult;
import com.github.pagehelper.PageInfo;
import com.it.annotation.ClearCache;
import com.it.annotation.SystemLog;
import com.it.bean.Menu;
import com.it.dto.MenuDTO;
import com.it.page.PageImpl;
import com.it.page.PageQuery;
import com.it.service.MenuService;
import com.it.vo.MenuVo;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/menu")
public class MenuController {

    private final MenuService menuService;

    @PostMapping("/page")
    @Cacheable(cacheNames = "menus", key = "T(java.util.Objects).hash(#pageQuery.page, #pageQuery.pageSize, #pageQuery.queryBody)")
    public SaResult page(@RequestBody PageQuery<MenuDTO> pageQuery) {
        PageInfo<MenuVo> pageInfo = menuService.page(pageQuery);
        return SaResult.data(PageImpl.of(pageInfo));
    }

    @PostMapping("/list")
    @Cacheable(cacheNames = "menus", key = "T(java.util.Objects).hash(#root.methodName)")
    public SaResult list(@RequestBody Menu menu) {
        List<Menu> menus = menuService.list(menu);
        return SaResult.data(menus);
    }

    @GetMapping("/nodes")
    @Cacheable(cacheNames = "menus", key = "T(java.util.Objects).hash(#root.methodName)")
    public SaResult nodes() {
        List<Menu> menus = menuService.nodes();
        return SaResult.data(menus);
    }

    @GetMapping("/tree")
    @Cacheable(cacheNames = "menus", key = "T(java.util.Objects).hash(#root.methodName)")
    public SaResult tree() {
        List<MenuVo> menuVo = menuService.tree();
        return SaResult.data(menuVo);
    }

    @ClearCache
    @PostMapping("/save")
    @SystemLog(value = "菜单管理", method = "新增修改")
    @CacheEvict(cacheNames = "menus", allEntries = true)
    @SaCheckPermission(value = {"menu-add", "menu-edit"}, orRole = {"admin"})
    public SaResult save(@RequestBody Menu menu) {
        menuService.save(menu);
        return SaResult.ok();
    }

    @ClearCache
    @PostMapping("/delete/{id}")
    @SystemLog(value = "菜单管理", method = "数据删除")
    @CacheEvict(cacheNames = "menus", allEntries = true)
    @SaCheckPermission(value = {"menu-delete"}, orRole = {"admin"})
    public SaResult delete(@PathVariable("id") Long id) {
        menuService.delete(id);
        return SaResult.ok();
    }

    @GetMapping("/underlings/{id}")
    public SaResult underlings(@PathVariable Long id) {
        List<Menu> menus = menuService.underlings(id);
        return SaResult.data(menus);
    }
}
